<template>
  <div class="app-container">
    <el-tabs ref="tabs" v-model="activeName">
      <el-tab-pane name="first">
        <el-form :model="queryParams" ref="assessListForm" size="small" :inline="true"
                 label-width="68px">
          <el-form-item prop="assessTemName">
            <el-input
              v-model="queryParams.assessTemName"
              placeholder="方案名称"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 150px"
            />
          </el-form-item>
          <input type="text" style="display: none;">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" type="warning" @click="resetQuery">重置</el-button>
          </el-form-item>

        </el-form>

        <el-table :data="assessRecordList" style="width: 100%">
          <el-table-column align="center" type="index" label="序号"></el-table-column>
          <el-table-column align="center" prop="assessName" label="考核名称"></el-table-column>
          <el-table-column align="center" prop="assessTemName" label="绩效方案"></el-table-column>
          <el-table-column align="center" prop="nickName" label="创建人"></el-table-column>
          <el-table-column align="center" prop="sumAssess" label="考核人数"></el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
          <el-table-column align="center" width="300" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="initiateAssess(scope.row)">发起考核</el-button>
              <el-button type="text" @click="getSecondEmp(scope.row)">查看人员</el-button>
              <el-button type="text" @click="changeProject(scope.row)">查看方案</el-button>
              <el-button type="text" @click="changeFlow(scope.row)">查看流程</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="assTotal>0"
          :total="assTotal"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination=" getList()"
        />
      </el-tab-pane>
      <el-dialog title="职能部门基础岗位绩效考核表" :before-close="closePreview" :visible.sync="previewIndex"
                 width="70%" center>
        <div>
          <el-table
            :data="targetResultVO"
            :span-method="objectSpanMethod"
            border
            style=" margin-top: 20px">
            <el-table-column align="center" prop="dimensionalityName" label="类别">
              <template slot-scope="scope">
                <span v-if="scope.row.dimensionalityName != null">{{ scope.row.dimensionalityName }}</span>
                <span v-if="scope.row.dimensionalityName == null">----</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="targetLabel" label="指标名称">
              <template slot-scope="scope">
                <span v-if="scope.row.targetLabel != null">{{ scope.row.targetLabel }}</span>
                <span v-if="scope.row.targetLabel == null">----</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="weight" label="权重">
              <template slot-scope="scope">
                <span v-if="scope.row.weight != null">{{ scope.row.weight + '%' }}</span>
                <span v-if="scope.row.weight == null">{{ 0 + '%' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="targetInfo" label="指标描述">
              <template slot-scope="scope">
                <span v-if="scope.row.targetInfo != null">{{ scope.row.targetInfo }}</span>
                <span v-if="scope.row.targetInfo == null">----</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="assessCriterion" label="计算方式">
              <template slot-scope="scope">
                <span v-if="scope.row.assessCriterion != null">{{ scope.row.assessCriterion }}</span>
                <span v-if="scope.row.assessCriterion == null">----</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
              <el-button @click="closePreview">关闭</el-button>
          </span>
      </el-dialog>

      <el-dialog title="考核流程" :visible.sync="centerDialogVisible" width="40%" center>
        <div style="height: 300px;">
          <el-steps direction="vertical">
            <el-step :title="activity.nickName +'  '+ activity.assessFlow"
                     v-for="(activity, index) in activities">
            </el-step>
          </el-steps>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
          </span>
      </el-dialog>
      <el-dialog title="发起考核" width="30%" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="ruleForm" label-position="right" label-width="110px" :model="assForm">
          <el-form-item prop="assessName" label="考核方案名称">
            <el-input style="width:230px" type="text" v-model="assForm.assessName"></el-input>
          </el-form-item>
          <el-form-item prop="assessPeriod" label="考核周期类型">
            <el-select v-model="assForm.assessPeriod" placeholder="请选择">
              <el-option value="月度"></el-option>
              <el-option value="季度"></el-option>
              <el-option value="年度"></el-option>
              <el-option value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="period" label="考核周期">
            <div class="block">
              <el-date-picker
                v-model="assForm.period"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit()">确 定</el-button>
        </div>
      </el-dialog>
      <el-tab-pane name="second">
        <el-button style="float: left;margin-right: 30px" @click="goFirstBack()">返回</el-button>
        <div style="margin-left: 100px">
          <h1>考核人员</h1>
        </div>
        <el-form :model="empParams" ref="empForm" size="small" :inline="true"
                 label-width="68px">
          <el-form-item prop="all">
            <el-input
              v-model="empParams.all"
              placeholder="方案名称"
              clearable
              @keyup.enter.native="handleEmpQuery"
              style="width: 150px"
            />
          </el-form-item>
          <input type="text" style="display: none;">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleEmpQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" type="warning" @click="resetEmpQuery">重置</el-button>
          </el-form-item>
          <div style="float: right">
            <el-button type="success" @click="addAssessEmp">新增考核人员</el-button>
          </div>
        </el-form>
        <el-dialog title="选择被考核人员" :visible.sync="dialogUser" width="70%">
          <el-row :gutter="20">
            <el-col :span="4" :xs="24">

              <div class="head-container">
                <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  default-expand-all
                  highlight-current
                  @node-click="handleNodeClick"
                />
              </div>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form :inline="true" :model="userParams">
                <el-form-item>
                  <el-input v-model="userParams.all">
                    <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
                <input type="text" class="form-control" style="display:none">
              </el-form>
              <el-table
                ref="staffTable"
                :key="tableKey"
                border
                fit
                height="500"
                highlight-current-row
                @selection-change="userIdsChange" :data="userList">
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"
                                 v-if="columns[2].visible" :show-overflow-tooltip="true"/>
                <el-table-column label="工号" align="center" key="jobNo" prop="jobNo" v-if="columns[7].visible"
                                 :show-overflow-tooltip="true"/>
              </el-table>
            </el-col>
            <el-col :span="2" :xs="24">
              <el-button
                @click="addStaff"
                type="primary"
                :disabled="!staffData.length"
                icon="el-icon-arrow-right"
                circle
              ></el-button>
              <el-button
                @click="removeStaff"
                type="primary"
                :disabled="!selectedStaffData.length"
                icon="el-icon-arrow-left"
                circle
                style="margin-left: 0;margin-top: 10px;"
              ></el-button>
            </el-col>
            <el-col :span="10">
              <div style="margin-bottom: 25px">
                <h3>已选（{{ names.length + '人' }}）</h3>
              </div>
              <el-table
                ref="selectedStaffTable"
                :key="tableKey"
                :data="names"
                border
                height="450"
                fit
                highlight-current-row
                @selection-change="handleSelectedStaffChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="昵称" align="center">
                  <template slot-scope="{row}">
                    <span>{{ row.nickName }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="工号" align="center" key="jobNo" prop="jobNo" v-if="columns[7].visible"
                                 :show-overflow-tooltip="true"/>
              </el-table>
              <div style="float: right;margin-top: 15px;margin-right: 20px">
                <el-button @click="dialogUser = false">取 消</el-button>
                <el-button type="primary" @click="changeInfo">确 定</el-button>
              </div>
            </el-col>
          </el-row>
        </el-dialog>
        <el-table
          :data="assessEmpList"
          style="width: 100%">
          <el-table-column align="center" prop="nickName" label="姓名"></el-table-column>
          <el-table-column align="center" prop="jobNo" label="工号"></el-table-column>
          <el-table-column align="center" prop="deptName" label="部门"></el-table-column>
          <el-table-column align="center" prop="stationName" label="岗位"></el-table-column>
          <el-table-column align="center" prop="status" label="员工状态">
            <template slot-scope="scope">
              <span v-if="scope.row.status === '3'" type="info">正式</span>
              <span v-if="scope.row.status === '4'" type="success">试用</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="workNature" label="工作性质"></el-table-column>
          <el-table-column align="center" prop="phone" label="手机号"></el-table-column>
        </el-table>
        <pagination
          v-show="empTotal>0"
          :total="empTotal"
          :page.sync="empParams.pageNum"
          :limit.sync="empParams.pageSize"
          @pagination="getEmpList()"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import Template from "@/views/system/email/ItoTemplate";
import {
  selectAssessRecord,
  getEmpListByAId,
  sponsorAssess,
  getUsers,
  updateEmp,
  getFlowByAid,
  getProjectByAid
} from '@/api/system/record'
import {listEmp} from '@/api/system/assess'
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "assessrecord",
  components: {Template, Treeselect},
  data() {
    return {
      createData: {},
      activities: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assessTemName: ''
      },
      tableKey: 0,
      staffData: [],
      selectedStaffData: [],
      empParams: {
        pageNum: 1,
        pageSize: 10,
        all: ''
      },
      assForm: {},
      previewIndex: false,
      targetResultVO: [],
      dialogFormVisible: false,
      dialogUser: false,
      centerDialogVisible: false,
      empTotal: 0,
      assTotal: 0,
      activeName: 'first',
      assessRecordList: [],
      assessEmpList: [],
      rules: {
        assessName: [
          {required: true, message: '方案名称不能为空', trigger: 'blur'}
        ],
        assessPeriod: [
          {required: true, message: '请选择活动区域', trigger: 'change'}
        ],
        period: [
          {
            type: 'array',
            required: true,
            message: '请选择日期区间',
            fields: {
              0: {type: 'date', required: true, message: '请选择开始日期'},
              1: {type: 'date', required: true, message: '请选择结束日期'}
            }
          }
        ]
      },
      userParams: {},
      names: [],
      tableSelect: [],
      userList: [],
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户昵称`, visible: true},
        {key: 3, label: `部门`, visible: true},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `状态`, visible: true},
        {key: 6, label: `创建时间`, visible: true},
        {key: 7, label: `工号`, visible: true}
      ],
      assessNode: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      InfoVo: {
        id: undefined,
        userIds: []
      },
      deptOptions: undefined,
      testArr1: [],
      testPosition1: 0
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
  },
  methods: {
    closePreview() {
      this.testArr1 = []
      this.testPosition1 = 0
      this.targetResultVO = []
      this.previewIndex = false
    },
    rowspan(spanArr, position, spanName) {
      this.targetResultVO.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1);
          position = 0;
        } else {
          if (
            this.targetResultVO[index][spanName] ===
            this.targetResultVO[index - 1][spanName]
          ) {
            spanArr[position] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            position = index;
          }
        }
      });
    },
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 0) {
        const _row = this.testArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    //查看流程
    changeFlow(row) {
      getFlowByAid(row.id).then(res => {
        this.activities = res.data
        this.centerDialogVisible = true
      })
    },
    //查看方案
    changeProject(row) {
      getProjectByAid(row.id).then(res => {
        this.previewIndex = true
        this.testArr1 = []
        this.testPosition1 = 0
        this.targetResultVO = res.data
        this.rowspan(this.testArr1, this.testPosition1, "dimensionalityName");
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    addAssessEmp() {
      this.dialogUser = true
      this.getUserList()
      getUsers(this.empParams.aid).then(res => {
        this.names = res.data
      })
    },
    getUserList() {
      listEmp(this.userParams).then(response => {
          this.userList = response.data;
        }
      );
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.userParams.deptId = data.id;
      this.getUserList();
    },
    // 隐藏表头中的全选框
    cellClass(row) {
      if (row.columnIndex === 0) {
        return 'disabledCheck'
      }
    },
    addStaff() {
      setTimeout(() => {
        this.$refs["staffTable"].clearSelection();
        this.$refs["selectedStaffTable"].clearSelection();
      }, 0);
      let repeat = false;
      this.names.forEach(item => {
        if (this.staffData[0] && item.userId === this.staffData[0].userId) {
          repeat = true;
          alert("此员工已添加");
          return;
        }
      });
      if (repeat === false) {
        this.staffData.forEach(item => {
          this.names.push(item);
        });
        for (let i = 0; i < this.userList.length; i++) {
          for (let j = 0; j < this.staffData.length; j++) {
            if (
              this.userList[i] &&
              this.staffData[j] &&
              this.userList[i].userId === this.staffData[j].userId
            ) {
              this.userList.splice(i, 1);
            }
          }
        }
      }
    },
    removeStaff() {
      setTimeout(() => {
        this.$refs["staffTable"].clearSelection();
        this.$refs["selectedStaffTable"].clearSelection();
      }, 0);
      this.selectedStaffData.forEach(item => {
        this.userList.push(item);
      });
      for (let i = 0; i < this.names.length; i++) {
        for (let j = 0; j < this.selectedStaffData.length; j++) {
          if (
            this.names[i] &&
            this.selectedStaffData[j] &&
            this.names[i].userId === this.selectedStaffData[j].userId
          ) {
            this.names.splice(i, 1);
          }
        }
      }
    },
    userIdsChange(val) {
      this.staffData = [];
      if (val) {
        val.forEach(row => {
          if (row) {
            this.staffData.push(row);
          }
        });
      }
    },
    // 将右边表格选择项存入selectedStaffData中
    handleSelectedStaffChange(rows) {
      this.selectedStaffData = [];
      if (rows) {
        rows.forEach(row => {
          if (row) {
            this.selectedStaffData.push(row);
          }
        });
      }
    },
    changeInfo() {
      if (this.names.length > 0) {
        this.InfoVo.userIds = this.names.map(i => i.userId)
        this.InfoVo.id = this.empParams.aid
        this.tableSelect.length = 0
        updateEmp(this.InfoVo).then(res => {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.getEmpList()
          this.dialogUser = false;
        })
        this.userIds = []
      } else {
        this.$message({
          message: '请选择至少一名被考核人员',
          type: 'warning'
        });
      }
    },
    initiateAssess(row) {
      console.log(row.id)
      this.assForm.aid = row.id
      this.dialogFormVisible = true
    },
    onSubmit() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          this.assForm.createTime = this.assForm.period[0]
          this.assForm.assessDeadline = this.assForm.period[1]
          this.$confirm('是否确认发起考核', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.dialogFormVisible = false
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            sponsorAssess(this.assForm).then(res => {
              this.$message({
                type: 'success',
                message: '开始考核'
              });

              loading.close();
              this.$router.push({path: '/performance/performanceindex', query: {}}).catch(() => {
              })
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消考核'
            });
          });

        }
      })
    },
    getList() {
      selectAssessRecord(this.queryParams).then(res => {
        console.log(res.rows)
        this.assessRecordList = res.rows
        this.assTotal = res.total
      })
    },
    handleQuery() {
      this.getList()
    },
    resetQuery() {
      this.queryParams.assessTemName = ''
      this.getList()
    },
    handleEmpQuery() {
      this.getEmpList()
    },
    resetEmpQuery() {
      this.empParams.all = ''
      this.getEmpList()
    },
    getEmpList() {
      getEmpListByAId(this.empParams).then(res => {
        this.assessEmpList = res.rows
        this.empTotal = res.total
      })
    },
    getSecondEmp(row) {
      this.empParams.aid = row.id
      getEmpListByAId(this.empParams).then(res => {
        this.assessEmpList = res.rows
        this.empTotal = res.total
        this.activeName = 'second'
      })
    },
    goFirstBack() {
      this.activeName = 'first'
      this.getList()
    }
  }
  ,
  mounted() {
    //tab标签的权限控制
    this.$nextTick(() => {
      //首先把所有的都隐藏
      this.$refs.tabs.$children[0].$refs.tabs[0].style.display = 'none';
      this.$refs.tabs.$children[0].$refs.tabs[1].style.display = 'none';
    });
  }
}
</script>

<style scoped>

</style>
